package tcp

import (
	"log"

	"github.com/pkg/errors"
	"github.com/plgd-dev/go-coap/v3/message/pool"
)

type HandlerFunc func(*Client, *pool.Message)

type IHandle interface {
	DoMsgHandler(*Client, *pool.Message)
	AddRouter(string, HandlerFunc)
}

type MsgHandle struct {
	MsgRouterMap map[string]HandlerFunc
}

func NewMsgHandle() *MsgHandle {
	return &MsgHandle{
		MsgRouterMap: make(map[string]HandlerFunc),
	}
}

func (mh *MsgHandle) DoMsgHandler(client *Client, request *pool.Message) {
	path, _ := request.Path()
	handerFunc, ok := mh.MsgRouterMap["receive"]
	if !ok {
		log.Printf("%+v", errors.WithStack(errors.Errorf("Handle router=%s not found", path)))
		return
	}
	handerFunc(client, request)

}

func (mh *MsgHandle) AddRouter(path string, router HandlerFunc) {
	if _, ok := mh.MsgRouterMap[path]; ok {
		log.Printf("%+v", errors.WithStack(errors.Errorf("Handle router=%s is registered", path)))
		return
	}
	mh.MsgRouterMap[path] = router
}
